package cn.car91.activity;

import java.net.URL;
import java.util.Date;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.adapter.CommentListAdapter;
import cn.car91.bean.Article;
import cn.car91.bean.ArticleComment;
import cn.car91.bean.User;
import cn.car91.http.HttpHandler;
import cn.car91.pager.CommentPager;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog;
import cn.car91.view.MyListView;
import cn.car91.view.VerticalScrollView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

public class ArticleDetailActivity extends BaseActivity {

	final int Request_Code = 21001;

	private CommentPager commentPager = new CommentPager();

	ArticleDetailHandler articleDetailHandler;

	LinearLayout comments;
	VerticalScrollView commentScroll;
	MyListView commentList;

	EditText commentContent;
	Button commentSubmitBtn;

	PopupWindow popupWindow;
	CommentListAdapter<ArticleComment> commentListAdapter;

	String title;
	String aid;

	boolean addDate = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_article_detail);
		super.onCreate(savedInstanceState);
		initView();

		aid = getIntent().getStringExtra("aid");

		if (RegexUtil.isNotNull(aid)) {
			HttpHandler.httpHandler.getArticleDetail(aid, callbackDetail);
		}

		comments = (LinearLayout) getLayoutInflater().inflate(
				R.layout.view_article_comment, null);
		commentContent = (EditText) comments
				.findViewById(R.id.article_detail_comment_content);
		commentSubmitBtn = (Button) comments
				.findViewById(R.id.article_detail_comment_submit);
		comments.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				comments.requestFocus();
				return false;
			}
		});
		commentSubmitBtn.setOnClickListener(onSubmitClickListener);

		commentList = (MyListView) comments
				.findViewById(R.id.article_detail_comment_list);
		commentListAdapter = new CommentListAdapter(ArticleDetailActivity.this,
				R.layout.view_article_comment_item);
		commentList.setAdapter(commentListAdapter);

		commentScroll = (VerticalScrollView) comments
				.findViewById(R.id.article_detail_comment_scroll);
		commentScroll.setOnTouchListener(onScrollTouchListener);
	}

	/* 详情页面 */
	private class ArticleDetailHandler {
		public TextView articleTitle;
		public TextView articleTime;
		public TextView articleAuthor;
		public WebView articleContent;
		public TextView articleScan;
	}

	private void initView() {
		articleDetailHandler = new ArticleDetailHandler();
		articleDetailHandler.articleTitle = (TextView) findViewById(R.id.article_detail_title);
		articleDetailHandler.articleTime = (TextView) findViewById(R.id.article_detail_time);
		articleDetailHandler.articleAuthor = (TextView) findViewById(R.id.article_detail_author);
		articleDetailHandler.articleContent = (WebView) findViewById(R.id.article_detail_content);
		articleDetailHandler.articleScan = (TextView) findViewById(R.id.article_detail_scan);
		articleDetailHandler.articleContent
				.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
		WebSettings webSettings = articleDetailHandler.articleContent
				.getSettings();
		webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webSettings.setUseWideViewPort(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setJavaScriptEnabled(true);
	}

	/**
	 * 页面显示商家信息
	 *
	 * @param article
	 *            商家
	 */
	private void initData(Article article) {
		if (articleDetailHandler != null && article != null) {
			title = article.getTitle();
			articleDetailHandler.articleTitle.setText(title);

			articleDetailHandler.articleTime.setText(DateFormat.format(
					"yy-MM-dd kk:mm", article.getTime()));

			if (article.getUser() != null)
				articleDetailHandler.articleAuthor.setText(article.getUser()
						.getName());
			else
				articleDetailHandler.articleAuthor
						.setText(R.string.article_detail_author_default);

			String style = "<style>img,p,div,table,fieldset,blockquote,section,span{max-width: 100%;height: auto;}</style>";
			articleDetailHandler.articleContent
					.loadDataWithBaseURL(
							getCar91Application().getArticleServerUrl(),
							"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no\"/>"
									+ style + article.getContent(),
							"text/html", "utf-8", null);
			articleDetailHandler.articleScan.setText(String.valueOf(article
					.getScan()));

			((TextView) findViewById(R.id.header_text)).setText(article
					.getTitle());
		} else {
			new HerilyAlertDialog.Builder(ArticleDetailActivity.this)
					.setMessage("该文章被限制浏览\n或已被删除").create().show();
		}
	}

	private OnTouchListener onScrollTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View arg0, MotionEvent arg1) {
			// TODO Auto-generated method stub
			switch (arg1.getAction()) {
			case MotionEvent.ACTION_UP:
				doOnBorderListener();
				break;
			}
			return false;
		}

		private void doOnBorderListener() {
			/*
			 * if (popupWindow != null) { if (popupWindow.isShowing()) {
			 * popupWindow.dismiss(); return; } }
			 */

			if (commentList != null
					&& commentList.getMeasuredHeight() <= commentScroll
							.getScrollY() + commentScroll.getHeight()) {
				// 底部
				addDate = true;
				getData();
			} else if (commentScroll.getScrollY() == 0) {
				// 顶部
			}
		}
	};

	/**
	 * 回调获取文章详情
	 */
	private RequestCallBack callbackDetail = new RequestCallBack() {

		@Override
		public void onFailure(HttpException arg0, String arg1) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "网络不给力啊~",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onSuccess(ResponseInfo arg0) {
			// TODO Auto-generated method stub
			initData((Article) Car91JsonUtil.getDTO(arg0.result.toString(),
					Article.class));
		}
	};

	OnClickListener onSubmitClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			User user = getCar91Application().getUser();
			if (user != null) {
				String content = commentContent.getText().toString();
				if (RegexUtil.isNotNull(content)) {
					HttpHandler.httpHandler.addArticleComment(aid,
							user.getId(), content, callBackSubmit);
				} else {
					new HerilyAlertDialog.Builder(ArticleDetailActivity.this)
							.setMessage("请输入内容").setNegativeButton("确认", null)
							.create().show();
				}
			} else {
				new HerilyAlertDialog.Builder(ArticleDetailActivity.this)
						.setMessage("请先登录")
						.setPositiveButton("登录",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface arg0,
											int arg1) {
										// TODO Auto-generated method stub
										Intent intent = new Intent();
										intent.setClass(
												ArticleDetailActivity.this,
												UserLoginActivity.class);
										startActivityForResult(intent,
												Request_Code);
									}
								}).setNegativeButton("取消", null).create()
						.show();
			}
		}
	};

	private void getData() {
		commentPager.getArticleComment(aid, callBackComment);
	}

	@OnClick(R.id.comment_btn)
	public void onCommentClick(View arg0) {
		// TODO Auto-generated method stub
		if (comments != null) {
			View parent = findViewById(R.id.article_detail);
			if (popupWindow == null) {
				getData();

				popupWindow = new PopupWindow(comments);
				popupWindow.setHeight((int) (parent.getMeasuredHeight() * 1.1));
				popupWindow.setWidth((int) (parent.getMeasuredWidth() * 1));
				popupWindow
						.setAnimationStyle(R.style.article_comment_popu_anim_style);
				// 需要设置一下此参数，点击外边可消失
				popupWindow.setBackgroundDrawable(new BitmapDrawable());
				popupWindow.setOutsideTouchable(true);
				// 设置弹出窗体需要软键盘，
				popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
				// 再设置模式，和Activity的一样，覆盖。
				popupWindow
						.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
				popupWindow.setFocusable(true);

				popupWindow.showAtLocation(parent, Gravity.LEFT, 0, 28);
			} else {
				if (!popupWindow.isShowing()) {
					popupWindow.showAtLocation(parent, Gravity.LEFT, 0, 28);
				}
			}
		}
	}

	// 分享功能
	UMSocialService mController = UMServiceFactory
			.getUMSocialService("com.umeng.share");
	String urlImage = "http://app.car91.cn/androidServer/download_apk.gif";
	String urlReader = "http://app.car91.cn/share.jsp?aid=" + aid;
	String urlDowan = "http://app.car91.cn/shareAPP.jsp";

	// 分享功能监听
	@OnClick(R.id.share_btn)
	public void onShareClick(View view) {
		mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN,
				SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE,
				SHARE_MEDIA.SINA, SHARE_MEDIA.TENCENT, SHARE_MEDIA.DOUBAN,
				SHARE_MEDIA.RENREN);
		// 设置分享内容
		mController
				.setShareContent("查违章！看实时路况！找优质维修店！找拖车师傅！对，扫我下载 “汽车点修网”，解决你的所有烦恼！");
		// 设置分享图片, 参数2为图片的url地址
		mController.setShareMedia(new UMImage(this, urlImage));
		// 人人网分享
		mController.setAppWebSite(SHARE_MEDIA.RENREN,
				"http://www.umeng.com/social");
		// 微信分享
		String appID = "wx5523e39ec95353f7";
		String appSecret = "ebf3997bbb09cea9cca0f1812bc0b3ac";
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(this, appID, appSecret);
		wxHandler.addToSocialSDK();
		// 支持微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(this, appID, appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
		// 分享到QQ
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, "1104756852",
				"HHcTseIyfNa57jtK");
		qqSsoHandler.addToSocialSDK();
		// 分享到QQ空间
		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this,
				"1104756852", "HHcTseIyfNa57jtK");
		qZoneSsoHandler.addToSocialSDK();

		mController.openShare(this, false);

		// 设置微信好友分享内容
		WeiXinShareContent weixinContent = new WeiXinShareContent();
		// 设置分享文字
		weixinContent
				.setShareContent("查违章！看实时路况！找优质维修店！找拖车师傅！对，扫我下载 “汽车点修网”，解决你的所有烦恼！");
		// 设置title
		weixinContent.setTitle("汽车点修网");
		// 设置分享内容跳转URL
		weixinContent.setTargetUrl(aid);
		// 设置分享图片
		weixinContent.setShareImage(null);
		mController.setShareMedia(weixinContent);
		// 设置微信朋友圈分享内容
		CircleShareContent circleMedia = new CircleShareContent();
		circleMedia
				.setShareContent("查违章！看实时路况！找优质维修店！找拖车师傅！对，扫我下载 “汽车点修网”，解决你的所有烦恼！");
		// 设置朋友圈title
		circleMedia.setTitle("汽车点修网");
		circleMedia.setShareImage(null);
		circleMedia.setTargetUrl(aid);
		mController.setShareMedia(circleMedia);

		// 设置分享内容
		QQShareContent qqShareContent = new QQShareContent();
		// 设置分享文字
		qqShareContent
				.setShareContent("查违章！看实时路况！找优质维修店！找拖车师傅！对，扫我下载 “汽车点修网”，解决你的所有烦恼！");
		// 设置分享title
		qqShareContent.setTitle("汽车点修网");
		// 设置分享图片
		qqShareContent.setShareImage(new UMImage(this, urlImage));
		// 设置点击分享内容的跳转链接
		qqShareContent.setTargetUrl(urlReader);
		mController.setShareMedia(qqShareContent);
		// 设置分享内容
		QZoneShareContent qzone = new QZoneShareContent();
		// 设置分享文字
		qzone.setShareContent("查违章！看实时路况！找优质维修店！找拖车师傅！对，扫我下载 “汽车点修网”，解决你的所有烦恼！");
		// 设置点击消息的跳转URL
		qzone.setTargetUrl(urlReader);
		// 设置分享内容的标题
		qzone.setTitle("汽车点修网");
		// 设置分享图片
		qzone.setShareImage(new UMImage(this, urlImage));
		mController.setShareMedia(qzone);

	}

	RequestCallBack callBackComment = new RequestCallBack() {

		@Override
		public void onFailure(HttpException arg0, String arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSuccess(ResponseInfo arg0) {
			// TODO Auto-generated method stub
			List<ArticleComment> comments = Car91JsonUtil.getDTOList(
					arg0.result.toString(), ArticleComment.class);
			if (comments.size() > 0) {
				if (addDate) {
					commentListAdapter.addData(comments);
				} else {
					commentListAdapter.setData(comments);
				}
				commentListAdapter.notifyDataSetChanged();
				addDate = true;
			}
		}
	};

	RequestCallBack callBackSubmit = new RequestCallBack() {
		@Override
		public void onStart() {
			// TODO Auto-generated method stub
			commentSubmitBtn.setEnabled(false);
			commentContent.setEnabled(false);
			super.onStart();
		}

		@Override
		public void onFailure(HttpException arg0, String arg1) {
			// TODO Auto-generated method stub
			commentSubmitBtn.setEnabled(true);
			commentContent.setEnabled(true);
		}

		@Override
		public void onSuccess(ResponseInfo arg0) {
			// TODO Auto-generated method stub
			Log.v("this", "字符串：" + arg0.result.toString());
			if (arg0.result.toString().equals("1")) {
				List<ArticleComment> comments = commentListAdapter.getData();
				ArticleComment comment = new ArticleComment();
				comment.setUsername(getCar91Application().getUser().getName());
				comment.setTime(new Date());
				comment.setContent(commentContent.getText().toString());
				comments.add(0, comment);
				commentListAdapter.setData(comments);
				commentListAdapter.notifyDataSetChanged();

				commentContent.setText("");
				commentSubmitBtn.setEnabled(true);
				commentContent.setEnabled(true);
				ArticleDetailActivity.this.comments.requestFocus();
			} else {
				Toast.makeText(ArticleDetailActivity.this, "发表失败",
						Toast.LENGTH_SHORT).show();
				commentSubmitBtn.setEnabled(true);
				commentContent.setEnabled(true);
			}

		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == Request_Code) {
			switch (resultCode) {
			case Car91ResultCode.Refresh_User_Code:
				commentSubmitBtn.performClick();
				break;
			default:
				break;
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

}
